<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>个人中心 - 鲜时蔬</title>
    <!-- 引入Vue.js框架，用于构建用户界面 -->
    <script src="../../js/vue.js"></script>
    <!-- 引入Element UI样式文件，提供组件样式 -->
    <link rel="stylesheet" href="../../css/index.css">
    <!-- 引入Element UI组件库，提供UI组件 -->
    <script src="../../js/index.js"></script>
    <!-- 引入axios库，用于发送HTTP请求 -->
    <script src="../../js/axios.min.js"></script>
    <!-- 引入vue-qriously生成二维码 -->
    <script src="../../js/vue-qriously.js"></script>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
            background-color: #f5f7fa;
            color: #333;
        }

        /* 布局样式 */
        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
        }

        .personal-center {
            display: flex;
            gap: 20px;
        }

        /* 侧边栏 */
        .sidebar {
            width: 250px;
            background: #fff;
            border-radius: 8px;
            box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
        }

        .user-profile {
            padding: 20px;
            text-align: center;
            border-bottom: 1px solid #eee;
        }

        .user-avatar {
            width: 80px;
            height: 80px;
            border-radius: 50%;
            background: #27ae60;
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 24px;
            margin: 0 auto 10px;
        }

        .user-name {
            font-size: 16px;
            font-weight: bold;
            margin-bottom: 5px;
        }

        .user-email {
            color: #999;
            font-size: 14px;
        }

        .menu {
            padding: 10px 0;
        }

        .menu-item {
            padding: 12px 20px;
            cursor: pointer;
            transition: background 0.3s;
        }

        .menu-item:hover {
            background: #f5f7fa;
        }

        .menu-item.active {
            background: #ecf5ff;
            color: #27ae60;
            border-right: 3px solid #27ae60;
        }

        /* 主内容区 */
        .main-content {
            flex: 1;
            background: #fff;
            border-radius: 8px;
            box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
        }

        .content-header {
            padding: 20px;
            border-bottom: 1px solid #eee;
        }

        .content-body {
            padding: 20px;
        }

        /* 表单通用样式 */
        .profile-form, .merchant-register {
            max-width: 800px;
        }

        .form-section {
            margin-bottom: 30px;
        }

        .section-title {
            font-size: 18px;
            color: #27ae60;
            margin-bottom: 20px;
            padding-bottom: 10px;
            border-bottom: 2px solid #eee;
        }

        .form-row {
            display: flex;
            gap: 20px;
            margin-bottom: 20px;
        }

        .form-group {
            flex: 1;
        }

        .form-label {
            display: block;
            margin-bottom: 8px;
            font-weight: bold;
            color: #606266;
        }

        .form-input, .form-textarea, .form-select {
            width: 100%;
            padding: 10px 15px;
            border: 1px solid #dcdfe6;
            border-radius: 4px;
            font-size: 14px;
        }

        .form-input:focus, .form-textarea:focus, .form-select:focus {
            outline: none;
            border-color: #27ae60;
        }

        .form-textarea {
            min-height: 100px;
            resize: vertical;
        }

        .form-hint {
            font-size: 12px;
            color: #999;
            margin-top: 5px;
        }

        /* 文件上传 */
        .upload-area {
            border: 2px dashed #dcdfe6;
            border-radius: 6px;
            padding: 20px;
            text-align: center;
            cursor: pointer;
            transition: border 0.3s;
        }

        .upload-area:hover {
            border-color: #27ae60;
        }

        .upload-icon {
            font-size: 48px;
            color: #27ae60;
            margin-bottom: 10px;
        }

        .upload-text {
            color: #606266;
        }

        .file-list {
            margin-top: 15px;
        }

        .file-item {
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 8px;
            background: #f5f7fa;
            border-radius: 4px;
            margin-bottom: 8px;
        }

        .file-name {
            flex: 1;
            margin: 0 10px;
        }

        /* 按钮样式 */
        .submit-btn {
            background: #27ae60;
            color: white;
            border: none;
            padding: 12px 30px;
            border-radius: 4px;
            font-size: 16px;
            cursor: pointer;
            transition: background 0.3s;
        }

        .submit-btn:hover {
            background: #219653;
        }

        .submit-btn:disabled {
            background: #c0c4cc;
            cursor: not-allowed;
        }

        /* 商家状态显示 */
        .merchant-status {
            padding: 20px;
            background: #f5f7fa;
            border-radius: 8px;
            margin-bottom: 20px;
        }

        .status-approved {
            color: #67c23a;
        }

        .status-pending {
            color: #e6a23c;
        }

        .status-rejected {
            color: #f56c6c;
        }

        /* 加载状态 */
        .loading-container {
            display: flex;
            justify-content: center;
            align-items: center;
            min-height: 200px;
        }

        /* 提示信息 */
        .error-message {
            color: #f56c6c;
            margin: 10px 0;
            padding: 10px;
            background: #fef0f0;
            border-radius: 4px;
            border-left: 4px solid #f56c6c;
        }

        .success-message {
            color: #67c23a;
            margin: 10px 0;
            padding: 10px;
            background: #f0f9eb;
            border-radius: 4px;
            border-left: 4px solid #67c23a;
        }

        /* 响应式设计 */
        @media (max-width: 768px) {
            .personal-center {
                flex-direction: column;
            }

            .sidebar {
                width: 100%;
                margin-bottom: 20px;
            }

            .form-row {
                flex-direction: column;
                gap: 10px;
            }
        }

        /* 表单列布局 */
        .form-row {
            display: flex;
            gap: 30px;
            margin-bottom: 20px;
        }

        .form-col {
            flex: 1;
        }

        /* 响应式设计优化 */
        @media (max-width: 768px) {
            .form-row {
                flex-direction: column;
                gap: 0;
            }
        }

        /* 表单区域美化 */
        .form-section {
            background: #fafafa;
            border-radius: 8px;
            padding: 20px;
            margin-bottom: 25px;
            border: 1px solid #ebeef5;
            box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
        }

        .form-section:hover {
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
            transition: box-shadow 0.3s ease;
        }

        .section-title {
            font-size: 18px;
            color: #27ae60;
            margin-bottom: 20px;
            padding-bottom: 10px;
            border-bottom: 2px solid #27ae60;
            font-weight: 600;
        }

        /* 表单项美化 */
        .el-form-item {
            margin-bottom: 22px;
        }

        .el-form-item__label {
            color: #606266;
            font-weight: 500;
        }

        /* 输入框美化 */
        .el-input__inner, .el-textarea__inner {
            border-radius: 4px;
            border: 1px solid #dcdfe6;
            transition: border-color 0.3s;
        }

        .el-input__inner:focus, .el-textarea__inner:focus {
            border-color: #27ae60;
            box-shadow: 0 0 0 2px rgba(39, 174, 96, 0.2);
        }

        /* 下拉选择框美化 */
        .el-select {
            width: 100%;
        }

        /* 按钮区域 */
        .form-actions {
            text-align: center;
            padding-top: 20px;
            border-top: 1px solid #eee;
            margin-top: 10px;
        }

        .submit-btn {
            min-width: 120px;
            height: 40px;
            font-size: 16px;
            font-weight: 500;
        }

        /* 表单提示文字 */
        .form-hint {
            color: #999;
            font-size: 12px;
        }

        /* 成功/错误提示美化 */
        .success-message, .error-message {
            border-radius: 6px;
            padding: 15px 20px;
            margin-bottom: 20px;
            display: flex;
            align-items: center;
            animation: fadeIn 0.3s ease;
        }

        .success-message {
            background: #f0f9eb;
            border-left: 4px solid #67c23a;
            color: #67c23a;
        }

        .error-message {
            background: #fef0f0;
            border-left: 4px solid #f56c6c;
            color: #f56c6c;
        }

        @keyframes fadeIn {
            from {
                opacity: 0;
                transform: translateY(-10px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        /* 表单项图标 */
        .el-form-item__label i {
            margin-right: 5px;
            color: #27ae60;
        }

        /* 头像上传容器 */
        .avatar-upload-container {
            display: flex;
            flex-direction: column;
            gap: 10px;
        }

        /* 头像预览容器 */
        .avatar-preview-container {
            display: flex;
            align-items: center;
            gap: 15px;
        }

        /* 小尺寸头像展示区域 */
        .current-avatar-small {
            width: 120px;
            height: 120px;
            border-radius: 50%;
            overflow: hidden;
            border: 1px solid #ebeef5;
            display: flex;
            align-items: center;
            justify-content: center;
            background: #f5f7fa;
        }

        .avatar-preview-small {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }

        .avatar-placeholder-small {
            width: 100%;
            height: 100%;
            background: #27ae60;
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 36px;
        }

        /* 小尺寸上传按钮 */
        .avatar-uploader-small .el-upload {
            border: 1px dashed #d9d9d9;
            border-radius: 4px;
            cursor: pointer;
            transition: border-color 0.3s;
            display: inline-block;
        }

        .avatar-uploader-small .el-upload:hover {
            border-color: #27ae60;
        }

        /* 头像提示文字 */
        .avatar-tip {
            font-size: 12px;
            color: #999;
            margin-top: 5px;
        }

        /* 侧边栏头像优化 */
        .sidebar .user-avatar {
            width: 80px;
            height: 80px;
            margin: 0 auto 10px;
        }

        /* 响应式设计 - 在小屏幕上进一步缩小头像 */
        @media (max-width: 768px) {
            .current-avatar-small {
                width: 80px;
                height: 80px;
            }

            .avatar-placeholder-small {
                font-size: 24px;
            }

            .sidebar .user-avatar {
                width: 60px;
                height: 60px;
            }
        }

        /* 头像区域独立排版样式 */
        .form-row:first-child {
            padding: 20px 0;
            margin-bottom: 30px;
            background: #f9f9f9;
            border-radius: 6px;
            border: 1px solid #ebeef5;
        }

        /* 头像区域标签 */
        .form-row:first-child .el-form-item__label {
            font-weight: 600;
            color: #333;
        }

        /* 头像上传容器居中显示 */
        .form-row:first-child .avatar-upload-container {
            align-items: center;
        }

        /* 响应式设计 - 小屏幕上的头像区域 */
        @media (max-width: 768px) {
            .form-row:first-child {
                padding: 15px;
            }

            .form-row:first-child .avatar-preview-container {
                justify-content: center;
            }
        }

        /* 头像区域的表单项 */
        .form-row:first-child .el-form-item {
            margin-bottom: 0;
        }

        /* 表单项间距调整 */
        .form-item-spacing {
            margin-bottom: 40px;
        }

        .form-item-spacing:last-child {
            margin-bottom: 0;
        }

        /* 响应式设计 - 在小屏幕上调整间距 */
        @media (max-width: 768px) {
            .form-item-spacing {
                margin-bottom: 30px;
            }
        }

        /* 调整表单列在小屏幕上的间距 */
        @media (max-width: 768px) {
            .form-row {
                gap: 15px;
            }
        }

        /* 订单列表 */
        .order-list {
            margin-top: 20px;
        }

        .order-card {
            border: 1px solid #ebeef5;
            border-radius: 8px;
            margin-bottom: 20px;
            box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
        }

        .order-header {
            padding: 15px 20px;
            background-color: #f5f7fa;
            border-bottom: 1px solid #ebeef5;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .order-info {
            display: flex;
            gap: 30px;
        }

        .order-status {
            font-weight: bold;
        }

        .status-pending {
            color: #e6a23c;
        }

        .status-shipped {
            color: #409eff;
        }

        .status-completed {
            color: #67c23a;
        }

        .status-cancelled {
            color: #909399;
        }

        .order-items {
            padding: 20px;
        }

        .item-row {
            display: flex;
            padding: 15px 0;
            border-bottom: 1px solid #eee;
        }

        .item-row:last-child {
            border-bottom: none;
        }

        .item-image {
            width: 80px;
            height: 80px;
            border-radius: 4px;
            margin-right: 15px;
        }

        .item-details {
            flex: 1;
        }

        .item-name {
            font-weight: bold;
            margin-bottom: 5px;
        }

        .item-spec {
            color: #999;
            font-size: 14px;
            margin-bottom: 5px;
        }

        .item-price {
            color: #e74c3c;
            font-weight: bold;
        }

        .item-quantity {
            width: 100px;
            text-align: center;
        }

        .item-shipping {
            width: 120px;
            text-align: center;
        }

        .shipping-status {
            padding: 3px 8px;
            border-radius: 4px;
            font-size: 12px;
        }

        .shipping-pending {
            background-color: #fdf6ec;
            color: #e6a23c;
        }

        .shipping-shipped {
            background-color: #ecf5ff;
            color: #409eff;
        }

        .order-footer {
            padding: 15px 20px;
            background-color: #f5f7fa;
            border-top: 1px solid #ebeef5;
            display: flex;
            justify-content: flex-end;
            align-items: center;
        }

        .order-total {
            font-size: 18px;
            font-weight: bold;
            margin-right: 20px;
        }

        .order-actions {
            display: flex;
            gap: 10px;
        }

        .btn {
            padding: 8px 15px;
            border-radius: 4px;
            cursor: pointer;
            border: none;
            font-size: 14px;
        }

        .btn-primary {
            background-color: #27ae60;
            color: white;
        }

        .btn-primary:hover {
            background-color: #219653;
        }

        .btn-secondary {
            background-color: #909399;
            color: white;
        }

        .btn-secondary:hover {
            background-color: #606266;
        }

        .btn-disabled {
            background-color: #c0c4cc;
            cursor: not-allowed;
        }

        .empty-orders {
            text-align: center;
            padding: 50px;
            color: #999;
        }

        .loading {
            text-align: center;
            padding: 50px;
        }

        /* 订单操作记录 */
        .order-activities {
            margin-top: 15px;
            padding-top: 15px;
            border-top: 1px dashed #eee;
        }

        .activity-title {
            font-weight: bold;
            margin-bottom: 10px;
        }

        .activity-item {
            display: flex;
            padding: 8px 0;
            font-size: 14px;
        }

        .activity-time {
            width: 160px;
            color: #999;
        }

        .activity-desc {
            flex: 1;
        }

        /* 响应式设计 */
        @media (max-width: 768px) {
            .item-row {
                flex-direction: column;
                gap: 10px;
            }

            .order-info {
                flex-direction: column;
                gap: 10px;
            }

            .order-footer {
                flex-direction: column;
                gap: 15px;
            }

            .order-total {
                margin-right: 0;
            }
        }
    </style>
</head>
<body>
<div id="app">
    <div class="container">
        <div class="personal-center">
            <!-- 侧边栏 -->
            <div class="sidebar">
                <!-- 修改个人信息模块中的用户信息展示部分 -->
                <div class="user-profile">
                    <div class="user-avatar">
                        <img
                                v-if="userInfo.avatar"
                                :src="userInfo.avatar"
                                class="user-avatar-img"
                                style="width: 100%; height: 100%; border-radius: 50%; object-fit: cover;"
                                :alt="userInfo.nickName || userInfo.userName">
                        <span v-else class="avatar-placeholder">
    {{ userInfo.nickName ? userInfo.nickName.charAt(0) : (userInfo.userName ? userInfo.userName.charAt(0) : 'U') }}
  </span>
                    </div>
                    <div class="user-name">{{ userInfo.nickName || userInfo.userName || '用户' }}</div>
                    <div class="user-email">{{ userInfo.email || '未设置邮箱' }}</div>
                </div>

                <div class="menu">
                    <div class="menu-item" :class="{ active: activeMenu === 'profile' }"
                         @click="activeMenu = 'profile'">个人信息
                    </div>
                    <div class="menu-item" :class="{ active: activeMenu === 'orders' }" @click="activeMenu = 'orders'">
                        我的订单
                    </div>
                    <div class="menu-item" :class="{ active: activeMenu === 'merchant' }"
                         @click="activeMenu = 'merchant'">注册商家
                    </div>
                    <div class="menu-item" :class="{ active: activeMenu === 'security' }"
                         @click="activeMenu = 'security'">账号安全
                    </div>
                </div>
            </div>

            <!-- 主内容区 -->
            <div class="main-content">
                <div class="content-header">
                    <h2>{{ menuTitles[activeMenu] }}</h2>
                </div>

                <div class="content-body">
                    <!-- 加载状态 -->
                    <div v-if="loading" class="loading-container">
                        <i class="el-icon-loading" style="font-size: 32px;"></i>
                        <span style="margin-left: 10px;">加载中...</span>
                    </div>

                    <!-- 错误提示 -->
                    <div v-else-if="loadError" class="error-message">
                        <i class="el-icon-error"></i>
                        <span style="margin-left: 5px;">{{ loadError }}</span>
                        <el-button type="text" @click="loadUserInfo" style="margin-left: 10px;">重试</el-button>
                    </div>

                    <!-- 修改个人信息模块 -->
                    <div v-else-if="activeMenu === 'profile'" class="profile-form">
                        <!-- 个人信息状态提示 -->
                        <div v-if="profileUpdateSuccess" class="success-message" @click="profileUpdateSuccess = false">
                            <i class="el-icon-success"></i>
                            <span style="margin-left: 5px;">个人信息保存成功！</span>
                        </div>

                        <el-form :model="profileForm" :rules="profileRules" ref="profileForm" label-width="120px">
                            <!-- 基础信息 section -->
                            <!-- 在基础信息 section 中添加头像上传 -->
                            <div class="form-row">
                                <div class="form-col">
                                    <!-- 修改基础信息 section 的布局 -->
                                    <div class="form-section">
                                        <h3 class="section-title">基础信息</h3>

                                        <!-- 头像单独占一排 -->
                                        <div class="form-row">
                                            <div class="form-col">
                                                <el-form-item label="头像">
                                                    <div class="avatar-upload-container">
                                                        <div class="avatar-preview-container">
                                                            <div class="current-avatar-small">
                                                                <img v-if="profileForm.avatar" :src="profileForm.avatar"
                                                                     class="avatar-preview-small" alt="头像预览">
                                                                <div v-else class="avatar-placeholder-small">
                                                                    <i class="el-icon-user-solid"></i>
                                                                </div>
                                                            </div>
                                                            <el-upload
                                                                    class="avatar-uploader-small"
                                                                    action="/vegetablemarketexpress/user/uploadAvatarImage"
                                                                    name="pic"
                                                                    :show-file-list="false"
                                                                    :on-success="handleAvatarSuccess"
                                                                    :before-upload="beforeAvatarUpload">
                                                                <el-button size="mini" type="primary">上传头像
                                                                </el-button>
                                                            </el-upload>
                                                        </div>
                                                        <div class="avatar-tip">jpg/png文件，大小不超过2MB</div>
                                                    </div>
                                                </el-form-item>
                                            </div>
                                        </div>

                                        <!-- 其他信息分两列显示 -->
                                        <div class="form-row">
                                            <div class="form-col">
                                                <el-form-item label="用户名" prop="userName" class="form-item-spacing">
                                                    <el-input v-model="profileForm.userName" placeholder="请输入用户名"
                                                              disabled>
                                                        <template slot="append">
                                                            <span class="form-hint">注册后不可修改</span>
                                                        </template>
                                                    </el-input>
                                                </el-form-item>
                                                <div style="margin: 20px 0;"></div>
                                                <el-form-item label="昵称" prop="nickName" class="form-item-spacing">
                                                    <el-input v-model="profileForm.nickName"
                                                              placeholder="请输入昵称"></el-input>
                                                </el-form-item>
                                                <div style="margin: 20px 0;"></div>
                                                <el-form-item label="手机号码" prop="phonenumber"
                                                              class="form-item-spacing">
                                                    <el-input v-model="profileForm.phonenumber"
                                                              placeholder="请输入手机号码"></el-input>
                                                </el-form-item>
                                            </div>

                                            <div class="form-col">
                                                <el-form-item label="电子邮箱" prop="email" class="form-item-spacing">
                                                    <el-input v-model="profileForm.email"
                                                              placeholder="请输入电子邮箱"></el-input>
                                                </el-form-item>
                                                <div style="margin: 20px 0;"></div>
                                                <el-form-item label="性别" prop="sex" class="form-item-spacing">
                                                    <el-select v-model="profileForm.sex" placeholder="请选择性别"
                                                               style="width: 100%;">
                                                        <el-option label="男" value="0"></el-option>
                                                        <el-option label="女" value="1"></el-option>
                                                        <el-option label="未知" value="2"></el-option>
                                                    </el-select>
                                                </el-form-item>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- 提交按钮区域 -->
                            <div class="form-actions">
                                <el-form-item>
                                    <el-button
                                            type="primary"
                                            :loading="profileSubmitting"
                                            @click=" submitProfile"
                                            class="submit-btn">
                                        保存个人信息
                                    </el-button>
                                </el-form-item>
                            </div>
                        </el-form>
                    </div>

                    <!-- 注册商家模块 -->
                    <div v-else-if="activeMenu === 'merchant'" class="merchant-register">
                        <!-- 商家状态显示 -->
                        <div v-if="merchantStatus.hasApplied" class="merchant-status">
                            <h3>商家申请状态</h3>
                            <p>当前状态:
                                <span :class="{
                                    'status-approved': merchantStatus.status === 'approved',
                                    'status-pending': merchantStatus.status === 'pending',
                                    'status-rejected': merchantStatus.status === 'rejected'
                                }">
                                    {{ statusText[merchantStatus.status] || '未知状态' }}
                                </span>
                            </p>
                            <p v-if="merchantStatus.merchantInfo && merchantStatus.merchantInfo.auditTime">
                                审核时间: {{ formatDate(merchantStatus.merchantInfo.auditTime) }}
                            </p>
                            <p v-if="merchantStatus.merchantInfo && merchantStatus.merchantInfo.auditRemark"
                               class="audit-remark">
                                审核备注: {{ merchantStatus.merchantInfo.auditRemark }}
                            </p>
                        </div>

                        <el-form :model="merchantForm" :rules="merchantRules" ref="merchantForm" label-width="120px">
                            <!-- 商家基本信息 -->
                            <div class="form-section">
                                <h3 class="section-title">商家基本信息</h3>

                                <el-form-item label="商家名称" prop="customerName">
                                    <el-input v-model="merchantForm.customerName"
                                              placeholder="请输入商家名称" :disabled="isFormDisabled"></el-input>
                                </el-form-item>

                                <el-form-item label="身份证号" prop="idCard">
                                    <el-input v-model="merchantForm.idCard" placeholder="请输入身份证号码"
                                              maxlength="18" :disabled="isFormDisabled"></el-input>
                                </el-form-item>

                                <el-form-item label="联系电话" prop="phone">
                                    <el-input v-model="merchantForm.phone" placeholder="请输入联系电话"
                                              :disabled="isFormDisabled"></el-input>
                                </el-form-item>

                                <el-form-item label="商家地址" prop="address">
                                    <el-input v-model="merchantForm.address" placeholder="请输入详细地址"
                                              :disabled="isFormDisabled"></el-input>
                                </el-form-item>
                            </div>

                            <!-- 资质证明 -->
                            <div class="form-section">
                                <h3 class="section-title">资质证明</h3>

                                <el-form-item label="身份证件" prop="idPhotograph">
                                    <el-upload
                                            action="/vegetablemarketexpress/customer/uploadIdImage"
                                            name="pic"
                                            :on-success="handleLicenseSuccess"
                                            :before-upload="beforeLicenseUpload"
                                            :file-list="licenseFiles"
                                            :limit="1"
                                            :disabled="isFormDisabled">
                                        <el-button size="small" type="primary" :disabled="isFormDisabled">点击上传
                                        </el-button>
                                        <div slot="tip" class="el-upload__tip">
                                            请上传身份证件扫描件（jpg/png格式，不超过2MB）
                                        </div>
                                    </el-upload>
                                </el-form-item>
                            </div>

                            <!-- 提交按钮控制（审核中/已通过时禁用） -->
                            <el-form-item>
                                <el-button
                                        type="primary"
                                        :loading="submitting"
                                        @click="submitMerchantApplication"
                                        :disabled="isFormDisabled || submitting">
                                    {{ merchantStatus.hasApplied ? '更新申请' : '提交申请' }}
                                </el-button>
                                <el-button
                                        v-if="merchantStatus.status === 'approved'"
                                        type="success"
                                        @click="goToMerchantCenter">
                                    进入商家中心
                                </el-button>
                            </el-form-item>
                        </el-form>
                    </div>
                    <!-- 账号安全模块 -->
                    <div v-else-if="activeMenu === 'security'">
                        <div v-if="passwordUpdateSuccess" class="success-message" @click="passwordUpdateSuccess = false">
                            <i class="el-icon-success"></i>
                            <span style="margin-left: 5px;">密码修改成功！</span>
                        </div>

                        <el-form :model="passwordForm" :rules="passwordRules" ref="passwordForm" label-width="120px">
                            <div class="form-section">
                                <h3 class="section-title">修改密码</h3>

                                <el-form-item label="旧密码" prop="oldPassword">
                                    <el-input type="password" v-model="passwordForm.oldPassword" placeholder="请输入旧密码"></el-input>
                                </el-form-item>

                                <el-form-item label="新密码" prop="newPassword">
                                    <el-input type="password" v-model="passwordForm.newPassword" placeholder="请输入新密码"></el-input>
                                </el-form-item>

                                <el-form-item label="确认密码" prop="confirmPassword">
                                    <el-input type="password" v-model="passwordForm.confirmPassword" placeholder="请再次输入新密码"></el-input>
                                </el-form-item>
                            </div>

                            <div class="form-actions">
                                <el-button
                                        type="primary"
                                        :loading="passwordSubmitting"
                                        @click="submitPassword">
                                    确认修改
                                </el-button>
                            </div>
                        </el-form>
                    </div>

                    <!-- 我的订单模块 -->
                    <div v-else-if="activeMenu === 'orders'">
                        <div v-if="orderLoading" class="loading">
                            <el-spinner style="margin: 50px auto;"></el-spinner>
                            <p>正在加载订单信息...</p>
                        </div>

                        <div v-else>
                            <div v-if="orders.length === 0" class="empty-orders">
                                <h3>暂无订单</h3>
                                <p>您还没有购买任何商品</p>
                                <el-button type="primary" @click="goToShopping" style="margin-top: 20px;">
                                    去购物
                                </el-button>
                            </div>

                            <div v-else class="order-list">
                                <div v-for="order in orders" :key="order.orderId" class="order-card">
                                    <div class="order-header">
                                        <div class="order-info">
                                            <div>订单编号: {{ order.orderNo }}</div>
                                            <div>下单时间: {{ formatDate(order.createTime) }}</div>
                                            <div>订单金额: <span style="color: #e74c3c;">¥{{ order.totalAmount }}</span></div>
                                        </div>
                                        <div class="order-status" :class="getOrderStatusClass(order)">
                                            {{ getOrderStatusText(order) }}
                                        </div>
                                    </div>

                                    <div class="order-items">
                                        <div v-for="item in order.orderItems" :key="item.itemId" class="item-row">
<!--                                            <div class="item-image" style="background-color: #f5f7fa; display: flex; align-items: center; justify-content: center;">-->
<!--                                                <i class="el-icon-shopping-bag" style="font-size: 24px; color: #999;"></i>-->
<!--                                            </div>-->
                                            <!-- 修改 item-image 部分 -->
                                            <div class="item-image">
                                                <img v-if="item.imageUrl" :src="item.imageUrl" :alt="item.productName"
                                                     @error="handleImageError($event)"
                                                     style="width: 80px; height: 80px; object-fit: cover; border-radius: 4px;">
                                                <i v-else class="el-icon-shopping-bag" style="font-size: 24px; color: #999;"></i>
                                            </div>

                                            <div class="item-details">
                                                <div class="item-name">{{ item.productName }}</div>
                                                <div class="item-spec">{{ item.productSpec || '默认规格' }}</div>
                                                <div class="item-price">¥{{ item.salePrice.toFixed(2) }}</div>
                                            </div>
                                            <div class="item-quantity">
                                                数量: {{ item.orderQuantity }}
                                            </div>
                                            <div class="item-shipping">
                                                <span class="shipping-status"
                                                      :class="item.sortingStatus === '1' ? 'shipping-shipped' : 'shipping-pending'">
                                                    {{ item.sortingStatus === '1' ? '已发货' : '未发货' }}
                                                </span>
                                            </div>
                                        </div>
                                    </div>

                                    <div class="order-activities" v-if="order.orderActs && order.orderActs.length > 0">
                                        <div class="activity-title">订单操作记录</div>
                                        <div v-for="act in order.orderActs" :key="act.orderactid" class="activity-item">
                                            <div class="activity-time">{{ formatDate(act.cztime) }}</div>
                                            <div class="activity-desc">{{ getOrderActText(act.actno) }} - {{ act.remark || '' }}</div>
                                        </div>
                                    </div>

                                    <div class="order-footer">
                                        <div class="order-total">
                                            合计: <span style="color: #e74c3c;">¥{{ order.totalAmount }}</span>
                                        </div>
                                        <div class="order-actions">
                                            <!-- 去支付按钮 -->
                                            <el-button
                                                    v-if="order.orderActs && order.orderActs.length > 0 && order.orderActs[0].actno === 0"
                                                    type="primary"
                                                    size="small"
                                                    @click="goToPay(order)">
                                                去支付
                                            </el-button>
                                            <el-button
                                                    v-if="canConfirmReceipt(order)"
                                                    type="primary"
                                                    size="small"
                                                    @click="confirmReceipt(order)">
                                                确认收货
                                            </el-button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <!-- 支付二维码弹窗 -->
    <el-dialog
            title="微信扫码支付"
            :visible.sync="showQRDialog"
            width="400px"
            :before-close="handleClose">
        <div class="qrcode-container">
            <div style="margin-bottom: 15px;">支付金额: ¥{{ totalAmount }}</div>
            <qriously v-if="codeUrl" :value="codeUrl" :size="256" />
            <div class="qrcode-status">
                订单状态: {{ payStatus }}
            </div>
            <div v-if="payStatus === '支付成功'" class="success-message">
                支付成功！
            </div>
        </div>
    </el-dialog>
</div>

<script>
    new Vue({
        el: '#app',
        data() {
            // 身份证验证函数
            const validateIdCard = (rule, value, callback) => {
                if (!value) {
                    return callback(new Error('请输入身份证号码'));
                }

                // 身份证号码正则表达式
                const idCardPattern = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
                if (!idCardPattern.test(value)) {
                    return callback(new Error('请输入正确的身份证号码'));
                }

                // 加强验证：校验生日和校验位
                if (value.length === 18) {
                    const year = value.substring(6, 10);
                    const month = value.substring(10, 12);
                    const day = value.substring(12, 14);

                    const birthday = new Date(year + '-' + month + '-' + day);
                    if (birthday.getFullYear() != year ||
                        (birthday.getMonth() + 1) != month ||
                        birthday.getDate() != day) {
                        return callback(new Error('身份证号码中的生日无效'));
                    }
                }

                callback();
            };

            // 邮箱验证函数
            const validateEmail = (rule, value, callback) => {
                if (!value) {
                    return callback(new Error('请输入电子邮箱'));
                }
                const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
                if (!emailPattern.test(value)) {
                    return callback(new Error('请输入正确的电子邮箱格式'));
                }
                callback();
            };

            // 手机号验证函数
            const validatePhone = (rule, value, callback) => {
                if (!value) {
                    return callback(new Error('请输入手机号码'));
                }
                const phonePattern = /^1[3-9]\d{9}$/;
                if (!phonePattern.test(value)) {
                    return callback(new Error('请输入正确的手机号码'));
                }
                callback();
            };

            return {
                activeMenu: 'profile', // 默认显示个人信息页面
                userInfo: {},
                loadError: '',

                menuTitles: {
                    profile: '个人信息',
                    orders: '我的订单',
                    address: '收货地址',
                    merchant: '注册商家',
                    security: '账号安全'
                },
                // 订单相关数据
                orders: [],
                loading: true,
                showQRDialog: false,
                codeUrl: '',
                payStatus: '等待支付',
                paymentSuccess: false,
                totalAmount: 0,
                profileSubmitting: false, // 新增这一行：初始化提交状态（默认未提交）
                profileUpdateSuccess: false,// 如果你也用了这个变量，同样需要在这里声明
                // 个人信息表单
                profileForm: {
                    userName: '',     // 用户名（不可修改）
                    nickName: '',     // 昵称
                    phonenumber: '',  // 手机号码（与User实体类一致）
                    email: '',        // 电子邮箱
                    sex: '',          // 性别（与User实体类一致）
                    avatar: '',
                },
                // 个人信息表单验证规则
                profileRules: {
                    userName: [
                        {required: true, message: '用户名不能为空', trigger: 'blur'}
                    ],
                    nickName: [
                        {required: true, message: '请输入昵称', trigger: 'blur'},
                        {min: 2, max: 20, message: '昵称长度在2到20个字符', trigger: 'blur'}
                    ],
                    phonenumber: [
                        {required: true, validator: validatePhone, trigger: 'blur'}
                    ],
                    email: [
                        {required: true, validator: validateEmail, trigger: 'blur'}
                    ],
                    sex: [
                        {required: true, message: '请选择性别', trigger: 'change'}
                    ],
                },

                // 商家注册状态（后端返回）
                merchantStatus: {
                    hasApplied: false, // 是否已提交申请
                    status: '', // pending=审核中, approved=已通过, rejected=已拒绝
                    merchantInfo: null // 已提交的商家信息
                },
                // 商家注册表单（字段与后端Customer实体类统一）
                merchantForm: {
                    customerName: '', // 商家名称（对应后端customerName）
                    idCard: '', // 身份证号
                    phone: '', // 联系电话
                    address: '', // 商家地址
                    idPhotograph: '' // 身份证照片路径（对应后端idPhotograph）
                },
                // 商家表单验证规则
                merchantRules: {
                    customerName: [
                        {required: true, message: '请输入商家名称', trigger: 'blur'},
                        {min: 2, max: 50, message: '商家名称长度在2到50个字符', trigger: 'blur'}
                    ],
                    idCard: [
                        {required: true, validator: validateIdCard, trigger: 'blur'}
                    ],
                    phone: [
                        {required: true, message: '请输入联系电话', trigger: 'blur'},
                        {pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur'}
                    ],
                    address: [
                        {required: true, message: '请输入商家地址', trigger: 'blur'},
                        {min: 5, max: 200, message: '地址长度在5到200个字符', trigger: 'blur'}
                    ],
                    idPhotograph: [
                        {required: true, message: '请上传身份证件', trigger: 'change'}
                    ]
                },
                // 商家相关文件上传
                licenseFiles: [],
                submitting: false, // 商家表单提交状态
                // 密码修改表单
                passwordForm: {
                    oldPassword: '',
                    newPassword: '',
                    confirmPassword: ''
                },
// 密码修改表单验证规则
                passwordRules: {
                    oldPassword: [
                        {required: true, message: '请输入旧密码', trigger: 'blur'}
                    ],
                    newPassword: [
                        {required: true, message: '请输入新密码', trigger: 'blur'},
                        {min: 6, max: 20, message: '密码长度在6到20个字符', trigger: 'blur'}
                    ],
                    confirmPassword: [
                        {required: true, message: '请再次输入新密码', trigger: 'blur'},
                        {validator: (rule, value, callback) => {
                                if (value !== this.passwordForm.newPassword) {
                                    callback(new Error('两次输入的密码不一致'));
                                } else {
                                    callback();
                                }
                            }, trigger: 'blur'}
                    ]
                },
                passwordSubmitting: false,
                passwordUpdateSuccess: false,


            }
        },
        computed: {
            statusText() {
                return {
                    'approved': '已通过',
                    'pending': '审核中',
                    'rejected': '已拒绝'
                }
            },
            // 判断商家表单是否应该禁用（审核中或已通过时）
            isFormDisabled() {
                return this.merchantStatus.status === 'pending' || this.merchantStatus.status === 'approved';
            }
        },
        mounted() {
            this.loadUserInfo();
        },
        methods: {
            // 格式化日期
            formatDate(dateString) {
                if (!dateString) return '';
                const date = new Date(dateString);
                return date.toLocaleString('zh-CN');
            },

            // 加载用户信息
            loadUserInfo() {
                this.loading = true;
                this.loadError = '';

                axios.get('/vegetablemarketexpress/user/checkLoginStatus', {withCredentials: true})
                    .then(response => {
                        if (response.data.code === 200) {
                            this.userInfo = response.data.data;
                            this,this.loadOrders();//加载订单
                            this.initProfileForm(); // 初始化个人信息表单
                            this.loadMerchantStatus(); // 加载商家状态
                        } else {
                            // 用户未登录，跳转至登录页
                            window.location.href = '/vegetablemarketexpress/html/front/login.html';
                        }
                    })
                    .catch(error => {
                        console.error('加载用户信息失败:', error);
                        this.loadError = '加载用户信息失败，请检查网络连接';
                        this.loading = false;
                    });
            },

            // 初始化个人信息表单
            initProfileForm() {
                if (this.userInfo) {
                    this.profileForm = {
                        userName: this.userInfo.userName || '',
                        nickName: this.userInfo.nickName || '',
                        phonenumber: this.userInfo.phonenumber || '', // 使用phonenumber字段
                        email: this.userInfo.email || '',
                        sex: this.userInfo.sex || '', // 使用sex字段
                        avatar: this.userInfo.avatar || ''
                    };
                    this.$nextTick(() => {
                        this.$forceUpdate();
                    });
                }
            },

            // 加载商家注册及审核状态
            loadMerchantStatus() {
                axios.post('/vegetablemarketexpress/customer/getMerchantStatus', {}, {withCredentials: true})
                    .then(response => {
                        this.loading = false;
                        if (response.data.code === 200) {
                            this.merchantStatus = response.data.data;
                            // 若已提交过申请，回显表单数据
                            if (this.merchantStatus.hasApplied && this.merchantStatus.merchantInfo) {
                                const info = this.merchantStatus.merchantInfo;
                                this.merchantForm = {
                                    customerName: info.customerName || '',
                                    idCard: info.idCard || '',
                                    phone: info.phone || '',
                                    address: info.address || '',
                                    idPhotograph: info.idPhotograph || ''
                                };
                                // 回显已上传的身份证照片
                                if (info.idPhotograph) {
                                    this.licenseFiles = [{
                                        name: '身份证照片',
                                        url: info.idPhotograph
                                    }];
                                } else {
                                    this.licenseFiles = [];
                                }
                            }
                        } else {
                            this.loadError = '加载商家状态失败: ' + (response.data.message || '未知错误');
                        }
                    })
                    .catch(error => {
                        console.error('加载商家状态失败:', error);
                        this.loading = false;
                        this.loadError = '加载商家状态失败，请重试';
                    });
            },

            // 头像上传前校验
            beforeAvatarUpload(file) {
                const isJPGOrPNG = file.type === 'image/jpeg' || file.type === 'image/png';
                const isLt2M = file.size / 1024 / 1024 < 2;

                if (!isJPGOrPNG) {
                    this.$message.error('上传文件只能是 JPG/PNG 格式!');
                    return false;
                }
                if (!isLt2M) {
                    this.$message.error('上传文件大小不能超过 2MB!');
                    return false;
                }

                return true;
            },

            // 头像上传成功
            handleAvatarSuccess(response, file) {
                if (response.code === 200) {
                    // 后端返回 {filePath: "图片地址", originName: "原文件名"}
                    const avatarUrl = response.data.filePath;

                    this.profileForm.avatar = avatarUrl;
                    this.userInfo.avatar = avatarUrl;

                    // 回显到头像预览
                    this.$forceUpdate();

                    this.$message.success('头像上传成功');
                } else {
                    this.$message.error('头像上传失败：' + (response.message || '未知错误'));
                }
            },

            // 提交个人信息
            submitProfile() {
                this.$refs.profileForm.validate((valid) => {
                    if (valid) {
                        this.profileSubmitting = true;
                        const apiUrl = '/vegetablemarketexpress/user/updateUser';
                        // 补充后端必需的 userId（从 userInfo 中获取，后端日志显示 user_id=19）
                        const submitData = {
                            ...this.profileForm,
                            userId: this.userInfo.userId || this.userInfo.user_id // 适配后端字段名（userId 或 user_id）
                        };

                        axios.post(apiUrl, submitData, {withCredentials: true}) // 发送包含 userId 的数据
                            .then(response => {
                                if (response.data.code === 200) {
                                    this.profileUpdateSuccess = true;
                                    this.userInfo = {...this.userInfo, ...submitData}; // 更新前端用户信息缓存
                                    setTimeout(() => this.profileUpdateSuccess = false, 3000);
                                } else {
                                    this.$message.error('保存失败：' + (response.data.message || '未知错误'));
                                }
                            })
                            .catch(error => {
                                console.error('提交个人信息失败:', error);
                                this.$message.error('保存失败，请检查网络后重试');
                            })
                            .finally(() => {
                                this.profileSubmitting = false;
                            });
                    } else {
                        this.$message.error('请完善表单信息并确保格式正确');
                    }
                });
            },

            // 商家资质文件上传前校验
            beforeLicenseUpload(file) {
                const isJPGOrPNG = file.type === 'image/jpeg' || file.type === 'image/png';
                const isLt2M = file.size / 1024 / 1024 < 2;

                if (!isJPGOrPNG) {
                    this.$message.error('上传文件只能是 JPG/PNG 格式!');
                    return false;
                }
                if (!isLt2M) {
                    this.$message.error('上传文件大小不能超过 2MB!');
                    return false;
                }

                return true;
            },

            // 身份证件上传成功
            handleLicenseSuccess(response, file) {
                if (response.code === 200) {
                    this.merchantForm.idPhotograph = response.data.url;
                    this.licenseFiles = [file];
                    // 后端返回 {filePath: "图片地址", originName: "原文件名"}
                    this.merchantForm.idPhotograph = response.data.filePath;
                    this.licenseFiles = [{
                        name: '身份证照片',
                        url: response.data.filePath
                    }];
                    this.$message.success('身份证照片上传成功');
                } else {
                    this.$message.error('照片上传失败：' + (response.message || '未知错误'));
                }
            },

            // 提交商家注册申请
            submitMerchantApplication() {
                this.$refs.merchantForm.validate((valid) => {
                    if (valid) {
                        this.submitting = true;
                        const apiUrl = '/vegetablemarketexpress/customer/insertCustomer';

                        // 若已提交过申请，补充customerId用于更新
                        if (this.merchantStatus.hasApplied && this.merchantStatus.merchantInfo.customerId) {
                            this.merchantForm.customerId = this.merchantStatus.merchantInfo.customerId;
                        }

                        axios.post(apiUrl, this.merchantForm, {withCredentials: true})
                            .then(response => {
                                if (response.data.code === 200) {
                                    const msg = this.merchantStatus.hasApplied ? '商家申请更新成功' : '商家申请提交成功';
                                    this.$message.success(msg + '，请等待审核');
                                    this.loadMerchantStatus(); // 重新加载状态
                                } else {
                                    this.$message.error('提交失败：' + (response.data.message || '未知错误'));
                                }
                            })
                            .catch(error => {
                                console.error('提交商家申请失败:', error);
                                this.$message.error('提交失败，请检查网络后重试');
                            })
                            .finally(() => {
                                this.submitting = false;
                            });
                    } else {
                        this.$message.error('请完善表单信息并确保格式正确');
                    }
                });
            },

            // 进入商家中心
            goToMerchantCenter() {
                window.location.href = '/vegetablemarketexpress/html/back/index.html';
            },
            // 提交密码修改
            submitPassword() {
                this.$refs.passwordForm.validate((valid) => {
                    if (valid) {
                        this.passwordSubmitting = true;
                        const apiUrl = '/vegetablemarketexpress/user/updatePassword';

                        const params = new URLSearchParams();
                        params.append('oldPassword', this.passwordForm.oldPassword);
                        params.append('newPassword', this.passwordForm.newPassword);

                        axios.post(apiUrl, params, {
                            withCredentials: true,
                            headers: {
                                'Content-Type': 'application/x-www-form-urlencoded'
                            }
                        })
                            .then(response => {
                                if (response.data.code === 200) {
                                    this.passwordUpdateSuccess = true;
                                    // 自动退出登录
                                    setTimeout(()=>{
                                        axios.get('/vegetablemarketexpress/user/logout', { withCredentials: true })
                                            .then(() => {
                                                // 清除本地缓存
                                                localStorage.clear();
                                                sessionStorage.clear();

                                                // 跳转到登录页
                                                window.location.href = '/vegetablemarketexpress/html/front/login.html';
                                            })
                                            .catch(() => {
                                                // 即使登出失败也强制跳转
                                                window.location.href = '/vegetablemarketexpress/html/front/login.html';
                                            });
                                    },1500);
                                } else {
                                    this.$message.error('修改失败：' + (response.data.message || '旧密码不正确'));
                                }
                            })
                            .catch(error => {
                                console.error('修改密码失败:', error);
                                this.$message.error('修改失败，请检查网络后重试');
                            })
                            .finally(() => {
                                this.passwordSubmitting = false;
                            });
                    } else {
                        this.$message.error('请完善表单信息并确保格式正确');
                    }
                });
            },

            // 订单相关方法
            loadOrders() {
                this.loading = true;
                axios.get('/vegetablemarketexpress/order/getUserOrders', {withCredentials: true})
                    .then(response => {
                        if (response.data.code === 200) {
                            this.orders = response.data.data.orders || [];
                            console.log("订单数据:", this.orders);
                        } else {
                            this.$message.error('加载订单失败: ' + (response.data.message || '未知错误'));
                        }
                    })
                    .catch(error => {
                        console.error('加载订单失败:', error);
                        this.$message.error('加载订单失败，请重试');
                    })
                    .finally(() => {
                        this.loading = false;
                    });
            },

            // 获取订单状态文本（基于orderact表中的状态）
            getOrderStatusText(order) {
                // 确保 orderActs 存在且不为空
                if (order && order.orderActs && Array.isArray(order.orderActs) && order.orderActs.length > 0) {
                    // 获取最新的订单操作记录
                    const latestAct = order.orderActs[0];
                    // 确保 latestAct 和 actno 存在
                    if (latestAct && latestAct.actno !== undefined) {
                        const statusMap = {
                            0: '待支付',
                            1: '已支付（待发货）',
                            2: '已发货（待接收）',
                            3: '已完成',
                            4: '已关闭',
                            5: '无效订单'
                        };
                        return statusMap[latestAct.actno] || '未知状态';
                    }
                }
                // 如果没有操作记录，根据商品发货状态判断
                if (order && order.orderItems && Array.isArray(order.orderItems)) {
                    const shippedItems = order.orderItems.filter(item => item.sortingStatus === '1');
                    if (shippedItems.length === order.orderItems.length) {
                        return '已发货（待接收）';
                    }
                }
                return '未知状态';
            },

            // 获取订单状态样式类
            getOrderStatusClass(order) {
                // 通过orderActs获取最新的订单状态
                if (order && order.orderActs && Array.isArray(order.orderActs) && order.orderActs.length > 0) {
                    const latestAct = order.orderActs[0]; // 获取最新的操作记录
                    const classMap = {
                        0: 'status-pending',
                        1: 'status-pending',
                        2: 'status-shipped',
                        3: 'status-completed',
                        4: 'status-cancelled',
                        5: 'status-cancelled',
                        10: 'status-pending'
                    };
                    return classMap[latestAct.actno] || '';
                }

                // 如果没有操作记录，根据商品发货状态判断
                if (order && order.orderItems && Array.isArray(order.orderItems)) {
                    const shippedItems = order.orderItems.filter(item => item.sortingStatus === '1');
                    if (shippedItems.length === order.orderItems.length) {
                        return 'status-shipped';
                    }
                }

                return '';
            },

            // 获取订单操作记录文本
            getOrderActText(actno) {
                const actMap = {
                    0: '待支付',
                    1: '已支付',
                    2: '已发货',
                    3: '已完成',
                    4: '已关闭',
                    5: '无效订单',
                    10: '部分发货提示'
                };
                return actMap[actno] || '未知操作';
            },

            // 判断是否可以确认收货（订单状态为已发货）
            canConfirmReceipt(order) {
                // 确保 orderActs 存在且不为空
                if (order && order.orderActs && Array.isArray(order.orderActs) && order.orderActs.length > 0) {
                    // 获取最新的订单操作记录
                    const latestAct = order.orderActs[0];
                    // 确保 latestAct 和 actno 存在
                    if (latestAct && latestAct.actno !== undefined) {
                        return latestAct.actno === 2; // 2-已发货（待接收）
                    }
                }

                // 如果没有操作记录，根据商品发货状态判断
                if (order && order.orderItems && Array.isArray(order.orderItems)) {
                    const shippedItems = order.orderItems.filter(item => item.sortingStatus === '1');
                    if (shippedItems.length === order.orderItems.length) {
                        return true; // 所有商品都已发货，可以确认收货
                    }
                }

                return false;
            },

            // 确认收货
            confirmReceipt(order) {
                console.log("尝试确认收货:", order);

                this.$confirm('确认收货后订单将变为已完成状态，是否确认收货？', '确认收货', {
                    confirmButtonText: '确认',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    axios.post('/vegetablemarketexpress/order/confirmReceipt', {
                        orderId: order.orderId,
                        orderNo: order.orderNo
                    }, {withCredentials: true})
                        .then(response => {
                            if (response.data.code === 200) {
                                this.$message.success('确认收货成功');
                                this.loadOrders(); // 重新加载订单
                            } else {
                                this.$message.error('确认收货失败: ' + (response.data.message || '未知错误'));
                            }
                        })
                        .catch(error => {
                            console.error('确认收货失败:', error);
                            this.$message.error('确认收货失败，请重试');
                        });
                }).catch(() => {
                    // 取消确认
                });
            },
            // 去购物
            goToShopping() {
                window.location.href = '/vegetablemarketexpress/html/front/index.html';
            },
            goToPay(order) {
                // 设置订单信息
                this.orderNo = order.orderNo;
                this.totalAmount = order.totalAmount;
                // 生成支付二维码
                this.generatePaymentQRCode(order.orderNo);
            },
            // 修改 generatePaymentQRCode 方法
            generatePaymentQRCode(orderNo) {
                // 使用新的接口，只传递订单编号
                axios.post('/vegetablemarketexpress/order/getNativeCodeUrlByOrderNo?orderNo=' + orderNo, {}, {withCredentials: true})
                    .then(response => {
                        if (response.data && response.data.code === 200) {
                            this.codeUrl = response.data.data.code_url;
                            this.showQRDialog = true;
                            this.startQueryPayStatus();
                        } else {
                            this.$message.error('获取支付二维码失败');
                        }
                    })
                    .catch(error => {
                        console.error('生成支付二维码失败:', error);
                        this.$message.error('网络错误，生成支付二维码失败');
                    });
            },

            // 开始轮询支付status
            startQueryPayStatus() {
                // 清除之前的定时器
                if (this.timer) {
                    clearInterval(this.timer);
                }

                // 每3秒查询一次支付status
                this.timer = setInterval(() => {
                    this.queryPayStatus();
                }, 3000);
            },

// 查询支付status
            queryPayStatus() {
                if (!this.orderNo) return;

                axios.get('/vegetablemarketexpress/order/getPayStatus/' + this.orderNo, {withCredentials: true})
                    .then(response => {
                        if (response.data && response.data.code === 200) {
                            this.payStatus = response.data.data.trade_state_desc;

                            if (this.payStatus === '支付成功') {
                                // 支付成功，更新订单状态
                                this.updateOrderStatus();
                                // 关闭定时器
                                clearInterval(this.timer);
                                this.showQRDialog = false;
                                // 提示用户支付成功
                                this.$message.success('支付成功！');
                            }
                        }
                    })
                    .catch(error => {
                        console.error('查询支付状态失败:', error);
                    });
            },

            // 更新订单status
            updateOrderStatus() {
                const updateData = {
                    orderNo: this.orderNo,
                    status: 1 // 1-已支付
                };

                axios.post('/vegetablemarketexpress/order/updateStatus', updateData, {withCredentials: true})
                    .then(response => {
                        if (response.data && response.data.code === 200) {
                            console.log('订单状态更新成功');
                            // 重新加载订单列表
                            this.loadOrdders();
                        } else {
                            console.error('订单状态更新失败');
                        }
                    })
                    .catch(error => {
                        console.error('更新订单状态失败:', error);
                    });
            },
            // 关闭对话框
            handleClose(done) {
                this.$confirm('确认关闭支付窗口？')
                    .then(_ => {
                        done();
                        if (this.timer) {
                            clearInterval(this.timer);
                        }
                    })
                    .catch(_ => {});
            },
        },
        watch: {
            activeMenu(newVal) {
                if (newVal === 'orders' && this.orders.length === 0) {
                    this.loadOrders();
                }
            }
        },
        handleImageError(event) {
            event.target.src = '/static/images/no-image.png';
        },

    });
</script>
</body>
</html>
